package edu.guigu.networkdemomvvm.network;

import java.util.List;

import edu.guigu.networkdemomvvm.nonsingle.User;
import edu.guigu.networkdemomvvm.single.SingleUser;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class GithubClient implements GithubApi {

    private GithubApi githubApi;
    private static GithubClient githubClient;

    public static GithubClient getInstance() {
        if (githubClient == null) {
            githubClient = new GithubClient();
        }
        return githubClient;
    }

    private GithubClient() {

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor) // 添加日志拦截器
                .build();
        // 步骤1：创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .client(okHttpClient)   // 添加okhttp(可不设置使用默认的内部okhttp)
                // Retrofit强大的一个功能,可直接添加转换器
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 步骤2：创建网络请求接口的实例（通过retrofit的方式）
        githubApi = retrofit.create(GithubApi.class);
    }


    @Override
    public Call<SingleUser> getUser(int id) {
        return githubApi.getUser(id);
    }

    @Override
    public Call<List<User>> listUsers() {
        return githubApi.listUsers();
    }
}
